﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Transactions;
using ZenSystemService.Api.Business;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Services;
using ZenSystemService.Api.Common;
using TencentCloud.Tdmq.V20200217.Models;
using TencentCloud.Omics.V20221128.Models;


namespace ZenSystemService.Api.Controllers
{
    [Route("api/course")]
    [ApiController]
    public class CourseController : ControllerBase
    {
        private readonly CourseService _courseService;

        private readonly UserService _userService;

        private readonly DTOBusiness _dTOBusiness;

        private readonly TraineeOrderService _traineeOrderService;

        private readonly RecommendTermService _recommendTermService;

        public CourseController(CourseService courseService, UserService userService, DTOBusiness dTOBusiness
            , TraineeOrderService traineeOrderService, RecommendTermService recommendTermService)
        {
            _courseService = courseService;
            _userService = userService;
            _dTOBusiness = dTOBusiness;
            _traineeOrderService = traineeOrderService;
            _recommendTermService = recommendTermService;
        }


        /// <summary>
        /// 获取课程类型信息列表
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetCourseTypeList")]
        public async Task<ReturnObjectT<List<CourseType>>> GetCourseTypeList(ReceiveObjectT<CourseTypeQuery> _receiveObjectT)
        {
            ReturnObjectT<List<CourseType>> returnObjectT = new ReturnObjectT<List<CourseType>>();
            IEnumerable<CourseType> list = await _courseService.GetCourseTypeListAsync(_receiveObjectT.Data.InstitutionId);
            List<CourseType> CourseTypeList = null;
            if (list != null)
                CourseTypeList = list.ToList();
            returnObjectT.Code = 1;
            returnObjectT.Data = CourseTypeList;
            return returnObjectT;
        }


        /// <summary>
        /// 获取某一天的课程信息列表
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetCourseListByDay")]
        public async Task<ReturnObjectT<List<Course>>> GetCourseListByDay(ReceiveObjectT<CourseQuery> _receiveObjectT)
        {
            ReturnObjectT<List<Course>> returnObjectT = new ReturnObjectT<List<Course>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            DateTime? date = null;
            if (!_receiveObjectT.Data.Date.IsNullOrEmpty())
            {
                date = Convert.ToDateTime(_receiveObjectT.Data.Date);
            }
            IEnumerable<Course> list = await _courseService.GetCoursesListAsync(_receiveObjectT.Data.InstitutionId, _receiveObjectT.Data.CoachId, date);

            List<Course> courseList = null;
            if (list != null)
                courseList = list.ToList();

            if (courseList != null && courseList.Count > 0)
            {
                for (int i = 0; i < courseList.Count; i++)
                {
                    courseList[i].CourseStatusTxt = ((CourseStatus)courseList[i].CourseStatus).GetDesc();
                    User _coachInfo= await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    courseList[i].CoachInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_coachInfo);
                    //  courseList[i].CoachInfo = await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    courseList[i].CourseTypeInfo = await _courseService.GetCourseTypeByIdAsync(courseList[i].CourseTypeId);
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = courseList;
            return returnObjectT;
        }

        /// <summary>
        /// 根据时间段获取课程信息列表
        /// </summary>0
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetCourseListByStartEndDays")]
        public async Task<ReturnObjectT<List<Course>>> GetCourseListByStartEndDays(ReceiveObjectT<CourseQuery2> _receiveObjectT)
        {
            ReturnObjectT<List<Course>> returnObjectT = new ReturnObjectT<List<Course>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            DateTime? startDate = null;
            if (!_receiveObjectT.Data.StartDate.IsNullOrEmpty())
            {
                startDate = Convert.ToDateTime(_receiveObjectT.Data.StartDate);
            }
            DateTime? endDate = null;
            if (!_receiveObjectT.Data.EndDate.IsNullOrEmpty())
            {
                endDate = Convert.ToDateTime(_receiveObjectT.Data.EndDate);
            }
            IEnumerable<Course> list = await _courseService.GetCoursesListAsync(_receiveObjectT.Data.InstitutionId, _receiveObjectT.Data.CoachId, startDate.Value, endDate.Value);
            List<Course> courseList = null;
            if (list != null)
                courseList = list.ToList();

            if (courseList != null && courseList.Count > 0)
            {
                for (int i = 0; i < courseList.Count; i++)
                {
                    courseList[i].CourseStatusTxt = ((CourseStatus)courseList[i].CourseStatus).GetDesc();
                    // courseList[i].CoachInfo = await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    User _coachInfo = await _userService.GetUserByIdAsync(courseList[i].CoachId);
                    courseList[i].CoachInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_coachInfo);

                    courseList[i].CourseTypeInfo = await _courseService.GetCourseTypeByIdAsync(courseList[i].CourseTypeId);
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = courseList;
            return returnObjectT;
        }

        /// <summary>
        /// 管理员添加课程
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
       [HttpPost("InstitutionAdminAddCourse")]
        public async Task<ReturnObject> InstitutionAdminAddCourse(ReceiveObjectT<AdminCourseAddRequest> _receiveObjectT)
        {
            ReturnObject returnObjectT = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;

            User CurrentUser = await _userService.GetUserByIdAsync(userid);
            if (!CurrentUser.InstitutionId.HasValue)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "该用户非机构用户";
                return returnObjectT;
            }

            AdminCourseAddRequest _courseAddRequest = _receiveObjectT.Data;
            int[] CoachIdArr = _courseAddRequest.CoachIdArr;
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                for (int i = 0; i < CoachIdArr.Length; i++)
                {
                    Course _course = new Course();
                    _course.CourseNumber = BaseBusiness.Instance.CreateCourseNumber();
                    _course.CoachId = _courseAddRequest.CoachIdArr[i];
                    _course.StartTime = Convert.ToDateTime(_courseAddRequest.StartTime);
                    _course.CourseDuration = _courseAddRequest.CourseDuration;
                    _course.EndTime = _course.StartTime.AddMinutes(_course.CourseDuration);
                    _course.CourseStatus = (int)CourseStatus.NotStarted;
                    _course.CourseTypeId = _courseAddRequest.CourseType;
                    _course.Enabled = "1";
                    _course.CreatedUserID = userid;
                    _course.CreatedDate = DateTime.Now;
                    _course.InstitutionId = CurrentUser.InstitutionId.Value;

                    //判断课程时间是否冲突
                    IEnumerable<Course> list = await _courseService.GetCoursesListAsync(_course.InstitutionId, _course.CoachId, Convert.ToDateTime(_receiveObjectT.Data.StartTime));
                    IList<Course> CourseList = null;
                    if (list != null)
                        CourseList = list.ToList();
                    if (CourseList != null && CourseList.Count > 0)
                    {
                        for (int m = 0; m < CourseList.Count; m++)
                        {
                            Course course = CourseList[m];
                            User CoachInfo = await _userService.GetUserByIdAsync(_course.CoachId);
                            if (course.StartTime >= _course.StartTime && course.StartTime < _course.EndTime)
                            {
                                returnObjectT.Code = 0;
                                returnObjectT.ErrorMsg = "教练[" + CoachInfo.RealName + "]选择的课程开始时间有课程未结束";
                                return returnObjectT;
                            }
                            if (course.EndTime > _course.StartTime && course.EndTime <= _course.EndTime)
                            {
                                returnObjectT.Code = 0;
                                returnObjectT.ErrorMsg = "教练[" + CoachInfo.RealName + "]选择的课程结束时间有课程未结束";
                                return returnObjectT;
                            }
                            if (!_courseService.CreateCourseAsync(ref _course))
                            {
                                returnObjectT.Code = 0;
                                returnObjectT.ErrorMsg = "创建课程失败";
                                return returnObjectT;
                            }
                        }
                    }
                }
                transScope.Complete();
            }
            returnObjectT.Code = 1;
            return returnObjectT;
        }



        /// <summary>
        /// 教练添加课程
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("InstitutionCoachAddCourse")]
        public async Task<ReturnObjectT<Course>> InstitutionCoachAddCourse(ReceiveObjectT<CoachCourseAddRequest> _receiveObjectT)
        {
            ReturnObjectT<Course> returnObjectT = new ReturnObjectT<Course>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            User CurrentUser = await _userService.GetUserByIdAsync(userid);
            if (!CurrentUser.InstitutionId.HasValue)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "该用户非机构用户";
                return returnObjectT;
            }
            CoachCourseAddRequest _courseAddRequest = _receiveObjectT.Data;

            Course _course = new Course();
            _course.CourseNumber = BaseBusiness.Instance.CreateCourseNumber();
            _course.CoachId = _courseAddRequest.CoachId;
            _course.StartTime = Convert.ToDateTime(_courseAddRequest.StartTime);
            _course.CourseDuration = _courseAddRequest.CourseDuration;
            _course.EndTime = _course.StartTime.AddMinutes(_course.CourseDuration);
            _course.CourseStatus = (int)CourseStatus.NotStarted;
            _course.CourseTypeId = _courseAddRequest.CourseType;
            _course.Enabled = "1";
            _course.CreatedUserID = userid;
            _course.CreatedDate = DateTime.Now;
            _course.InstitutionId = CurrentUser.InstitutionId.Value;

            //判断时间是否冲突
            IEnumerable<Course> list = await _courseService.GetCoursesListAsync(_course.InstitutionId, _courseAddRequest.CoachId, Convert.ToDateTime(_receiveObjectT.Data.StartTime));
            IList<Course> CourseList = null;
            if (list != null)
                CourseList = list.ToList();
            if (CourseList != null && CourseList.Count > 0)
            {
                for (int i = 0; i < CourseList.Count; i++)
                {
                    Course course = CourseList[i];
                    if (course.StartTime >= _course.StartTime && course.StartTime < _course.EndTime)
                    {
                        returnObjectT.Code = 0;
                        returnObjectT.ErrorMsg = "选择的课程开始时间有课程未结束";
                        return returnObjectT;
                    }
                    if (course.EndTime > _course.StartTime && course.EndTime <= _course.EndTime)
                    {
                        returnObjectT.Code = 0;
                        returnObjectT.ErrorMsg = "选择的课程结束时间有课程未结束";
                        return returnObjectT;
                    }
                }
            }

            if (_courseService.CreateCourseAsync(ref _course))
            {
                returnObjectT.Code = 1;
                returnObjectT.Data = _course;
            }
            else
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "创建课程失败";
            }
            return returnObjectT;

        }

        /// <summary>
        /// 删除课程信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("DeleteCourseInfo")]
        public async Task<ReturnObject> DeleteCourseInfo(ReceiveObjectT<CourseDetailQuery> _receiveObjectT)
        {
            ReturnObject _returnObject = new ReturnObject();

            Course _course = await _courseService.GetCourseByIdAsync(_receiveObjectT.Data.CourseId);
            if (_course == null)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "参数错误";
                return _returnObject;
            }
            if (_course.CourseStatus == (int)CourseStatus.Starting || _course.CourseStatus == (int)CourseStatus.Ended)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "已开始或已结束的课程无法删除";
                return _returnObject;
            }

            bool isSuccess = await _courseService.DeleteCourseAsync(_receiveObjectT.Data.CourseId);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "删除课程信息失败";
            }
            return _returnObject;
        }


        /// <summary>
        /// 教练修改课程信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("CoachUpdateCourseInfo")]
        public async Task<ReturnObjectT<Course>> CoachUpdateCourseInfo(ReceiveObjectT<CourseUpdateRequest> _receiveObjectT)
        {
            ReturnObjectT<Course> returnObjectT = new ReturnObjectT<Course>();

            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "用户未登录";
                return returnObjectT;
            }
            int userid = userModel.UserId;
            User CurrentUser = await _userService.GetUserByIdAsync(userid);
            if (!CurrentUser.InstitutionId.HasValue)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "该用户非机构用户";
                return returnObjectT;
            }


            CourseUpdateRequest _courseUpdateRequest = _receiveObjectT.Data;
            Course _course = await _courseService.GetCourseByIdAsync(_courseUpdateRequest.CourseId);

            if (_course == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "获取课程信息失败";
                return returnObjectT;
            }
            if (_course.CourseStatus == (int)CourseStatus.Starting || _course.CourseStatus == (int)CourseStatus.Ended)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "已开始或已结束的课程无法修改";
                return returnObjectT;
            }

            //时间冲突判断
            IEnumerable<Course> list = await _courseService.GetCoursesListAsync(_course.InstitutionId, userid, Convert.ToDateTime(_receiveObjectT.Data.StartTime));
            IList<Course> CourseList = null;
            if (list != null)
                CourseList = list.Where(item => item.CourseId != _courseUpdateRequest.CourseId).ToList();

            if (CourseList != null && CourseList.Count > 0)
            {
                for (int i = 0; i < CourseList.Count; i++)
                {
                    Course course = CourseList[i];
                    if (course.StartTime >= _course.StartTime && course.StartTime < _course.EndTime)
                    {
                        returnObjectT.Code = 0;
                        returnObjectT.ErrorMsg = "选择的课程开始时间有课程未结束";
                        return returnObjectT;
                    }
                    if (course.EndTime > _course.StartTime && course.EndTime <= _course.EndTime)
                    {
                        returnObjectT.Code = 0;
                        returnObjectT.ErrorMsg = "选择的课程结束时间有课程未结束";
                        return returnObjectT;
                    }
                }
            }
            _course.StartTime = Convert.ToDateTime(_courseUpdateRequest.StartTime);
            _course.CourseDuration = _courseUpdateRequest.CourseDuration;
            _course.EndTime = _course.StartTime.AddMinutes(_course.CourseDuration);
            bool isSuccess = await _courseService.UpdateCourseAsync(_course);
            if (isSuccess)
            {
                returnObjectT.Code = 1;
            }
            else
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "修改课程失败";
            }
            return returnObjectT;
        }



        /// <summary>
        /// 根据ID获取课程详情信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetCourseInfoById")]
        public async Task<ReturnObjectT<Course>> GetCourseInfoById(ReceiveObjectT<CourseDetailQuery> _receiveObjectT)
        {
            ReturnObjectT<Course> returnObjectT = new ReturnObjectT<Course>();
            Course _course = await _courseService.GetCourseByIdAsync(_receiveObjectT.Data.CourseId);
            if (_course == null)
            {
                returnObjectT.Code = 0;
                returnObjectT.ErrorMsg = "参数错误";
                return returnObjectT;
            }
            _course.CourseStatusTxt = ((CourseStatus)_course.CourseStatus).GetDesc();
            //_course.CoachInfo = await _userService.GetUserByIdAsync(_course.CoachId);
            User _coachInfo = await _userService.GetUserByIdAsync(_course.CoachId);
            _course.CoachInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_coachInfo);

            _course.CourseTypeInfo = await _courseService.GetCourseTypeByIdAsync(_course.CourseTypeId);
            returnObjectT.Code = 1;
            returnObjectT.Data = _course;
            return returnObjectT;
        }

        /// <summary>
        /// 根据课程ID获取课程学员信息
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetCourseTraineeInfoByCourseId")]
        public async Task<ReturnObjectT<IList<CourseTrainee>>> GetCourseTraineeInfoByCourseId(ReceiveObjectT<CourseDetailQuery> _receiveObjectT)
        {
            ReturnObjectT<IList<CourseTrainee>> returnObjectT = new ReturnObjectT<IList<CourseTrainee>>();

            List<CourseTrainee> list = await _courseService.GetCourseTraineeListByCourseId(_receiveObjectT.Data.CourseId);
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    User _user= await _userService.GetUserByIdAsync(list[i].TraineeId);
                    if (_user != null)
                        list[i].TraineeInfo = await _dTOBusiness.ReorganizeUserInfoResponseDTO(_user);
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = list;
            return returnObjectT;
        }

        /// <summary>
        /// 根据课程ID获取课程训练项信息列表
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("GetCourseTrainingItemInfoByCourseId")]
        public async Task<ReturnObjectT<IList<CourseTrainingItem>>> GetCourseTrainingItemInfoByCourseId(ReceiveObjectT<CourseDetailQuery> _receiveObjectT)
        {
            ReturnObjectT<IList<CourseTrainingItem>> returnObjectT = new ReturnObjectT<IList<CourseTrainingItem>>();
            List<CourseTrainingItem> list = await _courseService.GetCourseTrainingItemListByCourseIdAsync(_receiveObjectT.Data.CourseId);
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].TrainingItemInfo = await _courseService.GetTrainingItemInfoById(list[i].TrainingItemId);
                    list[i].CourseTrainingItemStateTxt = ((CourseTrainingItemState)list[i].CourseTrainingItemState).GetDesc();
                }
            }
            returnObjectT.Code = 1;
            returnObjectT.Data = list;
            return returnObjectT;
        }



        /// <summary>
        /// 绑定课程学员
        /// </summary>
        /// <returns></returns>
        [HttpPost("BindCourseTrainee")]
        public async Task<ReturnObject> BindCourseTrainee(ReceiveObjectT<BindCourseTraineeRequest> _receiveObjectT)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            int userid = userModel.UserId;

            BindCourseTraineeRequest _bindCourseTraineeRequest = _receiveObjectT.Data;

            if (_bindCourseTraineeRequest.TraineeIdArr == null || _bindCourseTraineeRequest.TraineeIdArr.Length == 0)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "请选择人员";
                return returnObject;
            }
            Course _course = await _courseService.GetCourseByIdAsync(_bindCourseTraineeRequest.CourseId);

            CourseType _courseType = await _courseService.GetCourseTypeByIdAsync(_course.CourseTypeId);

            int maxNum = _courseType.MaximumPeople.Value;

            if (_bindCourseTraineeRequest.TraineeIdArr.Length > maxNum)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "该课程最多选择"+ maxNum+"人学员";
                return returnObject;
            }

            List<CourseTrainee> HasCourseTraineeListt = await _courseService.GetCourseTraineeListByCourseId(_bindCourseTraineeRequest.CourseId);
            int hasCount= HasCourseTraineeListt==null ? 0 : HasCourseTraineeListt.Count;
            hasCount = hasCount + _bindCourseTraineeRequest.TraineeIdArr.Length;

            if (hasCount > maxNum)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "该课程最多绑定" + maxNum + "人学员";
                return returnObject;
            }


            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                for (int i = 0; i < _bindCourseTraineeRequest.TraineeIdArr.Length; i++)
                {
                    if (BaseBusiness.Instance.JudgeCourseTraineeIsExist(HasCourseTraineeListt, _bindCourseTraineeRequest.TraineeIdArr[i]) == false)
                    {
                        CourseTrainee _courseTrainee = new CourseTrainee();
                        _courseTrainee.CourseId = _bindCourseTraineeRequest.CourseId;
                        _courseTrainee.TraineeId = _bindCourseTraineeRequest.TraineeIdArr[i];
                        _courseTrainee.Enabled = "1";

                        //判断课程时间段 该学员有没有课
                        List<CourseTrainee> CurrentTraineeCourseTraineeList = await _courseService.GetCourseTraineeListByTraineeId(_courseTrainee.TraineeId);
                        if (CurrentTraineeCourseTraineeList != null && CurrentTraineeCourseTraineeList.Count > 0)
                        {
                            // CurrentTraineeCourseTraineeList = CurrentTraineeCourseTraineeList.Where(item => !item.FinishClassSignTime.HasValue).ToList();

                            IEnumerable<Course> notfinishedlist = await _courseService.GetNotFinishedCourseList(_course.InstitutionId);
                            List<Course> NotFinishedCourseList = null;
                            if(notfinishedlist!=null)
                                NotFinishedCourseList= notfinishedlist.ToList();
                            if (NotFinishedCourseList != null && NotFinishedCourseList.Count > 0)
                            {
                                int[] NotFinishedCourseIdArr= new int[NotFinishedCourseList.Count];
                                for (int j = 0; j < NotFinishedCourseList.Count; j++)
                                {
                                    NotFinishedCourseIdArr[j] = NotFinishedCourseList[i].CourseId;
                                }
                                CurrentTraineeCourseTraineeList = CurrentTraineeCourseTraineeList.Where(item => NotFinishedCourseIdArr.Contains(item.CourseId)).ToList();
                            }
                        
                            if (CurrentTraineeCourseTraineeList != null && CurrentTraineeCourseTraineeList.Count > 0)
                            {
                                for (int j = 0; j < CurrentTraineeCourseTraineeList.Count; j++)
                                {
                                    Course _currentCourse = await _courseService.GetCourseByIdAsync(CurrentTraineeCourseTraineeList[j].CourseId);
                                    if (_course.StartTime >= _currentCourse.StartTime && _course.StartTime < _currentCourse.EndTime)
                                    {
                                        User _traineeEntity = await _userService.GetUserByIdAsync(CurrentTraineeCourseTraineeList[0].TraineeId);
                                        returnObject.Code = 0;
                                        returnObject.ErrorMsg = "学员:" + _traineeEntity.RealName + "该时间段有课程 无法加入新课程";
                                        return returnObject;
                                    }
                                    if (_course.EndTime > _currentCourse.StartTime && _course.EndTime <= _currentCourse.EndTime)
                                    {
                                        User _traineeEntity = await _userService.GetUserByIdAsync(CurrentTraineeCourseTraineeList[0].TraineeId);
                                        returnObject.Code = 0;
                                        returnObject.ErrorMsg = "学员:" + _traineeEntity.RealName + "该时间段有课程 无法加入新课程";
                                        return returnObject;
                                    }
                                }
                            }
                        }

                        if (!_courseService.CreateCourseTrainee(ref _courseTrainee))
                        {
                            returnObject.Code = 0;
                            returnObject.ErrorMsg = "绑定课程学员信息失败";
                            return returnObject;
                        }
                    }
                }
                transScope.Complete();
            }
            returnObject.Code = 1;
            return returnObject;
        }


        /// <summary>
        /// 解绑课程学员
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("UnBindCourseTrainee")]
        public async Task<ReturnObject> UnBindCourseTrainee(ReceiveObjectT<UnBindCourseTraineeRequest> _receiveObjectT)
        {
            ReturnObject _returnObject = new ReturnObject();

            CourseTrainee _courseTrainee = await _courseService.GetCourseTraineeByIdAsync(_receiveObjectT.Data.CourseTraineeId);
            _courseTrainee.Enabled = "0";

            if (_courseTrainee.AttendClassSignTime.HasValue || _courseTrainee.FinishClassSignTime.HasValue)
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "该学员已签到或完成上课 无法解绑";
                return _returnObject;
            }

            bool isSuccess = await _courseService.UpdateCourseTraineeAsync(_courseTrainee);
            if (isSuccess)
            {
                _returnObject.Code = 1;
            }
            else
            {
                _returnObject.Code = 0;
                _returnObject.ErrorMsg = "解绑失败";
            }
            return _returnObject;
        }


        /// <summary>
        /// 获取训练项信息列表
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("GetTrainingItemList")]
        public async Task<ReturnObjectT<IList<TrainingItem>>> GetTrainingItemList()
        {
            ReturnObjectT<IList<TrainingItem>> _returnObjectT = new ReturnObjectT<IList<TrainingItem>>();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "用户未登录";
                return _returnObjectT;
            }
            int userid = userModel.UserId;
            User CurrentUser = await _userService.GetUserByIdAsync(userid);
            if (!CurrentUser.InstitutionId.HasValue)
            {
                _returnObjectT.Code = 0;
                _returnObjectT.ErrorMsg = "该用户非机构用户";
                return _returnObjectT;
            }
            IEnumerable<TrainingItem> list =await _courseService.GetTrainingItemListAsync(CurrentUser.InstitutionId.Value);
            IList<TrainingItem> TrainingItemList = null;
            if (list != null)
                TrainingItemList = list.ToList();
            _returnObjectT.Data = TrainingItemList;
            _returnObjectT.Code = 1;
            return _returnObjectT;
        }



        /// <summary>
        /// 绑定课程训练项
        /// </summary>
        /// <returns></returns>
        [HttpPost("BindCourseTrainingItem")]
        public async Task<ReturnObject> BindCourseTrainingItem(ReceiveObjectT<BindCourseTrainingItemRequest> _receiveObjectT)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            int userid = userModel.UserId;

            BindCourseTrainingItemRequest _bindCourseTrainingItemRequest = _receiveObjectT.Data;

            List<CourseTrainingItem> HasCourseTrainingItemLiist = await _courseService.GetCourseTrainingItemListByCourseIdAsync(_bindCourseTrainingItemRequest.CourseId);

            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                for (int i = 0; i < _bindCourseTrainingItemRequest.TrainingItemIdArr.Length; i++)
                {
                    if (BaseBusiness.Instance.JudgeCourseTrainingItemIsExist(HasCourseTrainingItemLiist, _bindCourseTrainingItemRequest.TrainingItemIdArr[i]) == false)
                    {
                        CourseTrainingItem _courseTrainingItem = new CourseTrainingItem();
                        _courseTrainingItem.CourseId = _bindCourseTrainingItemRequest.CourseId;
                        _courseTrainingItem.TrainingItemId = _bindCourseTrainingItemRequest.TrainingItemIdArr[i];
                        if (!_courseService.CreateCourseTrainingItem(ref _courseTrainingItem))
                        {
                            returnObject.Code = 0;
                            returnObject.ErrorMsg = "绑定课程训练项信息失败";
                            return returnObject;
                        }
                    }
                }
                transScope.Complete();
            }
            returnObject.Code = 1;
            return returnObject;
        }

        /// <summary>
        /// 解绑课程训练项
        /// </summary>
        /// <param name="_receiveObjectT"></param>
        /// <returns></returns>
        [HttpPost("UnBindCourseTrainingItem")]
        public async Task<ReturnObject> UnBindCourseTrainingItem(ReceiveObjectT<UnBindCourseTrainingItemRequest> _receiveObjectT)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }

            CourseTrainingItem _courseTrainingItem =await _courseService.GetCourseTrainingItemByIdAsync(_receiveObjectT.Data.CourseTrainingItemId);
            if (_courseTrainingItem.StartTrainingTime.HasValue || _courseTrainingItem.EndTrainingTime.HasValue)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "该课程训练项已开始或已结束 无法解绑";
                return returnObject;
            }

            bool isSuccess = await _courseService.DeleteCourseTrainingItem(_receiveObjectT.Data.CourseTrainingItemId);
            if (isSuccess)
            {
                returnObject.Code = 1;
            }
            else
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "解绑失败";
            }
            return returnObject;
        }


        /// <summary>
        /// 上课签到
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("AttendClassSign")]
        public async Task<ReturnObject> AttendClassSign(ReceiveObjectT<CourseSignInRequest> _receiveObject)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                int[] TraineeIdArr = _receiveObject.Data.TraineeIdArr;
                for (int i = 0; i < TraineeIdArr.Length; i++)
                {
                    int TraineeId = TraineeIdArr[i];
                    CourseTrainee _courseTrainee = await _courseService.GetCourseTraineeAsync(_receiveObject.Data.CourseId, TraineeId);
                    /*
                    if (_courseTrainee == null)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "未找到课程人员信息";
                        return returnObject;
                    }
                    if (_courseTrainee.AttendClassSignTime.HasValue)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "已签到无法再次签到";
                        return returnObject;
                    }*/
                    if (_courseTrainee == null)
                        continue;
                    _courseTrainee.AttendClassSignTime = DateTime.Now;
                    bool isSuccess = await _courseService.UpdateCourseTraineeAsync(_courseTrainee);
                    if (isSuccess == false)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "签到失败";
                        return returnObject;
                    }
                }

                Course _course = await _courseService.GetCourseByIdAsync(_receiveObject.Data.CourseId);
                _course.CourseStatus = (int)CourseStatus.Starting;
                bool saveIsSuccess = await _courseService.UpdateCourseAsync(_course);
                if (saveIsSuccess == false)
                {
                    returnObject.Code = 0;
                    returnObject.ErrorMsg = "签到失败";
                    return returnObject;
                }
                transScope.Complete();
            }
            returnObject.Code = 1;
            return returnObject;
        }



        /// <summary>
        /// 下课签到
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("FinishClassSign")]
        public async Task<ReturnObject> FinishClassSign(ReceiveObjectT<FinishClassSignRequest> _receiveObject)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            CourseTrainee _courseTrainee = await _courseService.GetCourseTraineeAsync(_receiveObject.Data.CourseId, _receiveObject.Data.TraineeId);
            if (_courseTrainee == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "未找到课程人员信息";
                return returnObject;
            }
            _courseTrainee.FinishClassSignTime = DateTime.Now;
            _courseTrainee.SaveImage = _receiveObject.Data.SaveImage;
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                bool isSuccess = await _courseService.UpdateCourseTraineeAsync(_courseTrainee);
                if (isSuccess == false)
                {
                    returnObject.Code = 0;
                    returnObject.ErrorMsg = "操作失败";
                    return returnObject;
                }

                Course _course = await _courseService.GetCourseByIdAsync(_receiveObject.Data.CourseId);
                if (_course == null)
                {
                    returnObject.Code = 0;
                    returnObject.ErrorMsg = "获取课程信息失败";
                    return returnObject;
                }

                CourseType _courseType = await _courseService.GetCourseTypeByIdAsync(_course.CourseTypeId);
                if (_courseType == null)
                {
                    returnObject.Code = 0;
                    returnObject.ErrorMsg = "获取课程类型信息失败";
                    return returnObject;
                }
                _course.CourseStatus = (int)CourseStatus.Starting;
                bool saveIsSuccess = await _courseService.UpdateCourseAsync(_course);
                if (saveIsSuccess == false)
                {
                    returnObject.Code = 0;
                    returnObject.ErrorMsg = "签出失败";
                    return returnObject;
                }

                if (_courseType.Type == 1)//私教课
                {
                    //课程剩余数-1
                    TraineeCourseSurplus _traineeCourseSurplus = await _traineeOrderService.GetTraineeCourseSurplus(_course.CourseTypeId, _receiveObject.Data.TraineeId, _course.CoachId);
                    if (_traineeCourseSurplus == null)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "获取课程剩余项信息失败";
                        return returnObject;
                    }
                    _traineeCourseSurplus.SurplusCourseNum = _traineeCourseSurplus.SurplusCourseNum - 1;
                    bool saveSumIsSuccess = await _traineeOrderService.UpdateTraineeCourseSurplusAsync(_traineeCourseSurplus);
                    if (!saveSumIsSuccess)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "操作失败";
                        return returnObject;
                    }
                }
                else
                {
                    //课程剩余数-1
                    List<TraineeCourseSurplus> TraineeCourseSurplusList = await _traineeOrderService.GetTraineeCourseSurplus(_course.CourseTypeId, _receiveObject.Data.TraineeId);
                    if (TraineeCourseSurplusList == null || TraineeCourseSurplusList.Count == 0)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "获取课程剩余项信息失败";
                        return returnObject;
                    }
                    TraineeCourseSurplus _traineeCourseSurplus = TraineeCourseSurplusList[0];
                    if (_traineeCourseSurplus == null)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "获取课程剩余项信息失败";
                        return returnObject;
                    }
                    _traineeCourseSurplus.SurplusCourseNum = _traineeCourseSurplus.SurplusCourseNum - 1;
                    bool saveSumIsSuccess = await _traineeOrderService.UpdateTraineeCourseSurplusAsync(_traineeCourseSurplus);
                    if (!saveSumIsSuccess)
                    {
                        returnObject.Code = 0;
                        returnObject.ErrorMsg = "操作失败";
                        return returnObject;
                    }
                }
                transScope.Complete();
            }
            returnObject.Code = 1;
            return returnObject;
        }

        /// <summary>
        /// 下课
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("FinishClass")]
        public async Task<ReturnObject> FinishClass(ReceiveObjectT<FinishClassRequest> _receiveObject)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            Course _course = await _courseService.GetCourseByIdAsync(_receiveObject.Data.CourseId);
            if (_course == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "获取课程信息失败";
                return returnObject;
            }
            _course.CourseStatus = (int)CourseStatus.Ended;
            bool saveIsSuccess = await _courseService.UpdateCourseAsync(_course);
            if (saveIsSuccess)
            {
                returnObject.Code = 1;
            }
            else
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "操作失败";
            }
            return returnObject;
        }

        /// <summary>
        /// 获取推荐项目信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetRecommendTermList")]
        public async Task<ReturnObjectT<RecommendTermDTO>> GetRecommendTermList(ReceiveObjectT<RecommendTermRequest> _receiveObject)
        {
            ReturnObjectT<RecommendTermDTO> returnObject = new ReturnObjectT<RecommendTermDTO>();

            IEnumerable<RecommendTerm> rtlist = await _recommendTermService.GetRecommendTermListAsync(_receiveObject.Data.InstitutionId);
            List<RecommendTerm> RecommendTermList = null;
            if (rtlist != null)
                RecommendTermList = rtlist.ToList();

            
            IEnumerable<RecommendTermCoach> rtclist = await _recommendTermService.GetRecommendTermCoachListAsync();

            List<RecommendTermCoach> RecommendTermCoachList = null;
            if (rtclist != null)
                RecommendTermCoachList = rtclist.ToList();


            IEnumerable<User> ulist = await _userService.GetAllUsersAsync();
            List<User> AllUserList = null;
            if (ulist != null)
                AllUserList = ulist.ToList();


            List<UserInfoResponse> CoachInfoList = new List<UserInfoResponse>();
            if (RecommendTermCoachList != null && RecommendTermCoachList.Count > 0)
            {
                for (int i = 0; i < RecommendTermCoachList.Count; i++)
                {
                    int CoachId = RecommendTermCoachList[i].CoachId;
                    if (BaseBusiness.Instance.ValidateUserIsExist(CoachInfoList, CoachId) == false)
                    { 
                        if(AllUserList!=null&& AllUserList.Count>0)
                        {
                            List<User> CurrentUserList= AllUserList.Where(item=>item.UserId== CoachId).ToList();
                            if (CurrentUserList != null && CurrentUserList.Count > 0)
                            {
                                CoachInfoList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(CurrentUserList[0]));
                            }

                        }
                    }
                }
            }
            RecommendTermDTO recommendTermDTO=new RecommendTermDTO();
            recommendTermDTO.RecommendTermList = RecommendTermList;
            recommendTermDTO.CoachInfo = CoachInfoList;
            returnObject.Code = 1;
            returnObject.Data = recommendTermDTO;

            /*
            if (RecommendTermList != null && RecommendTermList.Count > 0)
            {
                for (int i = 0; i < RecommendTermList.Count; i++)
                {
                    List<UserInfoResponse> CoachInfoList = new List<UserInfoResponse>();
                    if (RecommendTermCoachList != null)
                    {
                        List<RecommendTermCoach> CurrentRecommendTermCoachList= RecommendTermCoachList.Where(item=>item.RecommendTermId== RecommendTermList[i].RecommendTermId).ToList();
                        if (CurrentRecommendTermCoachList != null)
                        {
                            for (int j = 0; j < CurrentRecommendTermCoachList.Count; j++)
                            {
                                RecommendTermCoach _recommendTermCoach= CurrentRecommendTermCoachList[j];
                                if (AllUserList != null)
                                {
                                    List<User> CurrentUserList = AllUserList.Where(item => item.UserId == _recommendTermCoach.CoachId).ToList();
                                    if (CurrentUserList!= null)
                                    {
                                        for (int m = 0; m < CurrentUserList.Count; m++)
                                        {
                                            CoachInfoList.Add(await _dTOBusiness.ReorganizeUserInfoResponseDTO(CurrentUserList[m]));
                                        }
                                    }
                                }
                            }
                        }
                    }

                    RecommendTermList[i].CoachInfo = CoachInfoList;

                }
            }
            */

            return returnObject;
        }


        /// <summary>
        /// 申请代课
        /// </summary>
        /// <param name="_receiveObject"></param>
        /// <returns></returns>
        [HttpPost("ApplySubstituteCourse")]
        public async Task<ReturnObject> ApplySubstituteCourse(ReceiveObjectT<ApplySubstituteCourseRequest> _receiveObject)
        {
            ReturnObject returnObject = new ReturnObject();
            ZenSystemService.Api.Domain.UserModel userModel = this.User.ToUserModel();
            if (userModel == null)
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "用户未登录";
                return returnObject;
            }
            int userid = userModel.UserId;

            SubstituteCourseRecord _substituteCourseRecord = new SubstituteCourseRecord();
            _substituteCourseRecord.CourseId = _receiveObject.Data.CourseId;
            _substituteCourseRecord.SubstituteCoachId = _receiveObject.Data.SubstituteCoachId;
            _substituteCourseRecord.ConfirmStatus = 0;
            _substituteCourseRecord.CreatedUserID = userid;
            _substituteCourseRecord.CreatedDate = DateTime.Now;

            bool saveIsSuccess = await _courseService.AddSubstituteCourseRecord(_substituteCourseRecord);
            if (saveIsSuccess)
            {
                returnObject.Code = 1;
            }
            else
            {
                returnObject.Code = 0;
                returnObject.ErrorMsg = "操作失败";
            }
            return returnObject;
        }

    }
}
